package server.component;

import server.Request;
import server.Servlet;

import java.util.Map;

/**
 * @author 黄子濠
 * @date 2020/7/29 22:26
 */
public class Mapper {

    private Map<String,Host> hostMap;

    public Map<String, Host> getHostMap() {
        return hostMap;
    }

    public void setHostMap(Map<String, Host> hostMap) {
        this.hostMap = hostMap;
    }

    public Servlet findServlet(Request request){
        //根据host和port找出host对象
        Host host = hostMap.get(request.getHost() + ":" + request.getPort());
        //从host中获取contextMap
        Map<String, Context> contextMap = host.getContextMap();
        //根据请求路径的第一个路径，定位出context
        String url = request.getUrl();
        int i = url.indexOf("/", 2);
        String url_context = url.substring(1,i);
        String url_location = url.substring(i);
        Context context = contextMap.get(url_context);
        //从context中获取wrapper
        Map<String, Wrapper> wrapperMap = context.getWrapperMap();
        Wrapper wrapper = wrapperMap.get(url_location);
        //得到wrapper中的servlet并返回
        return wrapper.getServlet();
    }
}
